import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PanTaoHui {
    private static final int MAX_PEACHES = 5;
    private static int currentPeaches = 0;

    private static Lock lock = new ReentrantLock();
    private static Condition fullCondition = lock.newCondition();//果盘满状态
    private static Condition emptyCondition = lock.newCondition();//果盘空状态
    private static class Servant implements Runnable {
        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    // 当果盘不为空
                    while (currentPeaches > 0) {
                        emptyCondition.await();
                    }
                    // 当果盘为空
                    System.out.println("服务员装满桃子");
                    currentPeaches = MAX_PEACHES;
                    // 通知客人
                    fullCondition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
    private static class Guest implements Runnable {
        private int id;
        public Guest(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    // 当果盘为空时
                    while (currentPeaches == 0) {
                        fullCondition.await();
                    }
                    // 当果盘不为空时
                    System.out.println("客人" + id + "取走一个桃子");
                    currentPeaches--;
                    // 通知服务员
                    emptyCondition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
    public static void main(String[] args) {
        Thread servantThread = new Thread(new Servant());//服务员线程
        servantThread.start();
        for (int i = 1; i <= 10; i++) {
            Thread guestThread = new Thread(new Guest(i));//客人线程
            guestThread.start();
        }
    }
}